package han.message;

import com.han.http.client.method.HttpPost;
import com.han.http.client.paramter.FormDataPair;
import com.han.http.client.paramter.RequestHeader;
import com.han.http.fetch.Fetcher;
import han.entity.GroupEntity;
import han.entity.GroupMemberEntity;
import han.parser.GroupParser;
import han.proof.GroupWebsiteLogin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author: Han
 * @date: 2018/7/18 9:50
 * @dscription: 从QQ群官网获取群组信息
 */
public class GroupWebsite {

    private static Logger logger = LoggerFactory.getLogger(GroupWebsite.class);

    /**
     * 获取群组列表
     *
     * @throws Exception 抛出异常
     */
    public List<GroupEntity> getGroupList() throws Exception {
        String url = "https://qun.qq.com/cgi-bin/qun_mgr/get_group_list";
        RequestHeader[] requestHeaders = {
                new RequestHeader("%3Aauthority", "qun.qq.com"),
                new RequestHeader("%3Amethod", "POST"),
                new RequestHeader("%3Apath", "/cgi-bin/qun_mgr/get_group_list"),
                new RequestHeader("%3Ascheme", "https"),
                new RequestHeader("accept", "application/json, text/javascript, */*; q=0.01"),
                new RequestHeader("accept-encoding", "gzip, deflate, br"),
                new RequestHeader("accept-language", "zh-CN,zh;q=0.9"),
                new RequestHeader("content-length", "13"),
                new RequestHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"),
                new RequestHeader("cookie", GroupWebsiteLogin.getLoginCookie()),
                new RequestHeader("origin", "https://qun.qq.com"),
                new RequestHeader("referer", "https://qun.qq.com/member.html"),
                new RequestHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"),
                new RequestHeader("x-requested-with", "XMLHttpRequest")
        };
        FormDataPair[] formDataPairs = {
                new FormDataPair("bkn", GroupWebsiteLogin.getBkn() + "")
        };
        Fetcher fetcher = new Fetcher();
        int generalTimeout = 1000 * 10;
        String page = fetcher.getPageInfoByPost(url, requestHeaders, formDataPairs, generalTimeout, generalTimeout,
                false, HttpPost.UTF_8, null);

        //去掉空格
        page = page.replace("&nbsp;", " ");
        page = page.replace("&ensp;", " ");
        page = page.replace("&emsp;", " ");
        page = page.replace("&thinsp;", " ");
        page = page.replace("&amp;", "");
        //获取群列表
        List<GroupEntity> groupList = GroupParser.getGroupListFromGroupWebsite(page);
        Random random = new Random();
        int interval;
        //遍历群列表,获取每个群的群成员
        for (GroupEntity groupEntity : groupList) {
            interval = random.nextInt(1000 * 2) + 1000 * 2;
            try {
                String groupAccount = groupEntity.getGroupAccount() + "";
                //获取群成员列表,并放入群对象中
                Map<String, GroupMemberEntity> memberMap = searchGroupMembers(groupAccount);
                groupEntity.setMemberMap(memberMap);
            } catch (Exception e) {
                logger.error(groupEntity + "检索失败");
                logger.info(e.toString());
                StackTraceElement[] stackTraceElements = e.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTraceElements) {
                    logger.error(stackTraceElement.toString());
                }
            } finally {
                try {
                    //不管成功失败,都会休眠
                    Thread.sleep(interval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return groupList;
    }

    /**
     * 获取群组成员
     *
     * @param gc 群号
     * @return 群成员map
     * @throws Exception 抛出异常
     */
    private Map<String, GroupMemberEntity> searchGroupMembers(String gc) throws Exception {
        String url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members";
        RequestHeader[] headers = {
                new RequestHeader("%3Aauthority", "qun.qq.com"),
                new RequestHeader("%3Amethod", "POST"),
                new RequestHeader("%3Apath", "/cgi-bin/qun_mgr/search_group_members"),
                new RequestHeader("%3Ascheme", "https"),
                new RequestHeader("accept", "application/json, text/javascript, */*; q=0.01"),
                new RequestHeader("accept-encoding", "gzip, deflate, br"),
                new RequestHeader("accept-language", "zh-CN,zh;q=0.9"),
                new RequestHeader("content-length", "44"),
                new RequestHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"),
                new RequestHeader("cookie", GroupWebsiteLogin.getLoginCookie()),
                new RequestHeader("origin", "https://qun.qq.com"),
                new RequestHeader("referer", "https://qun.qq.com/member.html"),
                new RequestHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"),
                new RequestHeader("x-requested-with", "XMLHttpRequest")
        };
        FormDataPair[] formDataPairs = {
                new FormDataPair("gc", gc),
                new FormDataPair("st", "0"),
                new FormDataPair("end", "5000"),
                new FormDataPair("sort", "0"),
                new FormDataPair("bkn", GroupWebsiteLogin.getBkn() + "")
        };
        Fetcher fetcher = new Fetcher();
        String page = fetcher.getPageInfoByPost(url, headers, formDataPairs, 1000 * 10,
                1000 * 10, true, HttpPost.UTF_8, null);

        //去掉空格
        page = page.replace("&nbsp;", " ");
        page = page.replace("&ensp;", " ");
        page = page.replace("&emsp;", " ");
        page = page.replace("&thinsp;", " ");
        page = page.replace("&amp;", "");
        return GroupParser.getGroupMemberMapFromWebsite(page);
    }
}
